package com.service.admin.framework.interceptor;

import com.service.admin.admin.dto.LoginUserSession;
import com.service.admin.admin.service.SysUserService;
import com.service.admin.support.Language;
import com.service.admin.support.SessionUtil;
import com.service.admin.support.Token;
import com.service.admin.utils.LanguageUtil;
import com.service.core.http.OptionsRequestHandler;
import com.service.dao.enums.CommonStatusEnums;
import com.service.dao.model.Member;
import com.service.dao.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 */
@Component
@Slf4j
public class AdminAuthenticationInterceptor implements HandlerInterceptor {


    @Autowired
    private Environment env;

    @Autowired
    private SessionUtil sessionUtil;

    @Autowired
    private SysUserService sysUserService;

    @Value("${CROS_ALLOWED_ORIGINS}")
    private String[] allowedOrigins;

    @Value("${CROS_ALLOWED_METHOD}")
    private String allowedMethods;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //预检请求(用于处理跨域访问的复杂请求)

        boolean success = OptionsRequestHandler.handleOptions(request, response,  allowedOrigins, allowedMethods);
        if (success) {
            log.info("OPTIONS预检请求通过");
            return false;
        }
        LanguageUtil.deal();
        log.info("requestURI:{},after deal lang:{}", requestURI, Language.LANG.get());
        LoginUserSession loginUserSession = sessionUtil.getUserWithoutRedisTran();
        if (loginUserSession == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        SysUser sysUser = sysUserService.getSysUserDetailById(loginUserSession.getId());
        if(ObjectUtils.isEmpty(sysUser) || !Integer.valueOf(sysUser.getUserStatus() + "").equals(CommonStatusEnums.ACTIVE.getCode())){
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return false;
        }
        String existToken = sessionUtil.getSessionId(sysUser.getId());
        if (StringUtils.isEmpty(existToken)) {
            return true;
        }
        if (!StringUtils.equals(Token.TOKEN.get(), existToken)) {
            //其他地方登录
            response.setStatus(HttpStatus.CONFLICT.value());
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
